package constant.milk.cashbook.photo;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import constant.milk.cashbook.R;
import constant.milk.cashbook.data.DataMainActivity;
import constant.milk.cashbook.util.MilkUtil;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class CameraActivity extends Activity
{
	public static final String PASH = "PASH";

	private ViewGroup cameraView;
	private View shootingView;
	
	private CheckBox checkBox;

	private String path;

	private byte[] photoData;

	private MintSurfaceView msv;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.camera_activity);

		setFindView();
		setOnClickListener();
		setData();
	}

	private void setFindView()
	{
		cameraView = (ViewGroup) findViewById(R.id.cameraView);
		shootingView = findViewById(R.id.shootingView);
		checkBox = (CheckBox) findViewById(R.id.closeUpCheckBox);

		msv = new MintSurfaceView(this);
		
		cameraView.addView(msv);
	}

	private void setOnClickListener()
	{
		shootingView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				msv.setPhoto(new PictureCallback()
				{
					@Override
					public void onPictureTaken(byte[] data, Camera camera)
					{
						camera.stopPreview();

						photoData = data;

						new ShowDialog().execute(0);
					}
				});
			}
		});
		
		checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
		{
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
			{
				if (isChecked)
				{
					msv.closeUp();
				}
				else
				{
					msv.closeDown();
				}
			}
		});
	}

	private void setData()
	{
		path = "";
	}

	/**
	 * 다이얼로그 뛰우기
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>
	{
		ProgressDialog dialog = null;

		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
			dialog = new ProgressDialog(CameraActivity.this);
			dialog.setCancelable(false);
			dialog.setMessage("사진찍는중...");
			dialog.show();
		}

		@Override
		protected Integer doInBackground(Integer... arg0)
		{
			if (arg0[0] == 0)
			{
				FileOutputStream fos = null;
				ByteArrayInputStream bais = new ByteArrayInputStream(photoData);

				try
				{
					if (!Environment.MEDIA_MOUNTED.equals(Environment
							.getExternalStorageState()))
					{
						return 3;
					}
					
					File dir = new File(
							Environment.getExternalStorageDirectory() + "/"
									+ DataMainActivity.dirName);
					
					if (!dir.exists())
					{
						dir.mkdir();
					}

					File directory = new File(
							Environment.getExternalStorageDirectory() + "/"
									+ DataMainActivity.dirNamePhoto);

					if (!directory.exists())
					{
						directory.mkdir();
					}

					String directoryPath = directory.getPath();

					long timeStamp = System.currentTimeMillis();

					path = directoryPath + "/" + timeStamp + ".jpg";

					File writefile = new File(path);

					fos = new FileOutputStream(writefile);

					byte[] buffer = new byte[1024];

					int bufBytes = 0;

					while ((bufBytes = bais.read(buffer)) != -1)
					{
						fos.write(buffer, 0, bufBytes);
					}

					fos.flush();

				} catch (Exception e)
				{
					return 1;
				} finally
				{
					try
					{
						if (fos != null)
							fos.close();
						if (bais != null)
							bais.close();
					} catch (IOException e)
					{
						return 2;
					}
				}
			}

			return 0;
		}

		@Override
		protected void onPostExecute(Integer result)
		{
			super.onPostExecute(result);

			if (dialog != null)
			{
				dialog.dismiss();
			}

			if (result == 0)
			{
				MilkUtil.showToast(CameraActivity.this, "사진이 찍혔습니다.");
				Intent intent = new Intent();
				intent.putExtra(PASH, path);
				setResult(Activity.RESULT_OK, intent);
				finish();
			} 
			else if (result == 1)
			{
				MilkUtil.showToast(CameraActivity.this,
						"사진을 찍기가 실패하였습니다. 개발자에게 문의해 주세요.");
			} 
			else if (result == 2)
			{
				MilkUtil.showToast(CameraActivity.this,
						"사진을 찍기가 실패하였습니다. 개발자에게 문의해 주세요.");
			} 
			else if (result == 3)
			{
				MilkUtil.showToast(CameraActivity.this,
						"컴퓨터에서 연결을 해제한후 사진을 찍어주세요.");
			}
		}
	}
}
